package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse
import com.aliyuncs.exceptions.ClientException

@Transactional
@CompileStatic
@TypeChecked
class MessageService
{
    static scope = "singleton"
    SendSMSService sendSMSService

    //返回值为[statusCode:message],如果调成功statusCode为0,如果调用失败statusCode为错误代码,message里为错误原因
    def sendMessage2(String apiUrl, String cellphone, String templete)
    {
        // println "sendMessage2"
        // def map = [:]
        // // map['verifyCode'] = "123456"
        // // map['externalName'] = "快贷"
        // map['taskCode'] = "123456"
        // def params = map as JSON
        //
        // def message = new Message()
        // message.platform = "阿里"
        // message.text = "SMS_77445055"
        // message.cellphone = cellphone
        // message.save()
        //
        // try {
        //     // sendSMSService.sendSms("18510004280","快贷","【快贷】您的“externalName”验证码为:verifyCode，10分钟内有效", params.toString());
        //     SendSmsResponse response = sendSMSService.sendSms(cellphone, "智慧估价", templete, params.toString())
        //     if(null != response && response.getCode().equals("OK")){
        //         message.status = "Succesful"
        //         message.returnCode = response.getCode()
        //         message.save()
        //         return true;
        //     }else {
        //         println("短信发送失败，号码："+cellphone +"模板："+templete +"数据："+ params +"原因："+response.getMessage());
        //         message.status = "Failed"
        //         message.returnCode = response.getCode()
        //         message.returnMessage = response.getMessage()
        //         message.save()
        //     }
        // } catch (ClientException e) {
        //     e.printStackTrace();
        // }

        return false;
    }

    //返回值为[statusCode:message],如果调成功statusCode为0,如果调用失败statusCode为错误代码,message里为错误原因
    def sendMessage3(String cellphone, String text)
    {
        // def response
        //
        // def corpId = "kaijingyz"
        // def pwd = "8FTeR5dA"
        // def encode = "UTF-8"
        //
        // def errors = ["00": "多个手机号请求发送成功",
        //     "02": "IP限制",
        //     "03": "单个手机号请求发送成功",
        //     "04": "用户名错误",
        //     "05": "密码错误",
        //     "07": "发送时间有误",
        //     "08": "内容有误",
        //     "09": "手机号码有误",
        //     "10": "扩展号码有误",
        //     "11": "余额不足",
        //     "-1": "服务器内部异常"]
        //
        // def message = new Message()
        // message.platform = "领选互联"
        // message.text = text
        // message.cellphone = cellphone
        // message.save()
        //
        // URL url = new URL("http://101.200.29.88:8082/SendMT/SendMessage")
        // HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        // connection.setDoOutput(true)
        // connection.setRequestMethod("POST")
        // //            connection.setRequestProperty("Accept-Charset",encode)
        //
        // def params = "CorpID=" + URLEncoder.encode(corpId, encode) + "&Pwd=" + URLEncoder.encode(pwd, encode) + "&Mobile=" + URLEncoder.encode(cellphone, encode) + "&Content=" + URLEncoder.encode(text, encode)
        //
        // println params
        //
        // connection.outputStream.withWriter { Writer writer -> writer.write params }
        // response = connection.inputStream.withReader { Reader reader -> reader.text }
        //
        // def result = response.toString().split(",")
        // def code = result[0]
        //
        // println code
        //
        // if (code in ["00", "03"])
        // {
        //     message.status = "Succesful"
        //     message.returnCode = result[0]
        //     message.save()
        // }
        // else
        // {
        //     message.status = "Failed"
        //     message.returnCode = result[0]
        //     message.returnMessage = errors[result[0]]
        //     message.save()
        //
        //     return [statusCode: code.toInteger(), message: message.returnMessage]
        // }

        // log.message = message
        // message.save flush: true
        // log.save flush: true
        [statusCode: 0, message: "OK"]
    }

    def sendVerifyMessage(String cellphone, String verifyCode)
    {
        println "sendVerifyMessage"
        def signName = "信达泰和"
        def template = "SMS_120125796"
        def map = [:]
        map['verifyCode'] = verifyCode
        def params = map as JSON

        def message = new Message()
        message.platform = "阿里"
        message.text = template
        message.cellphone = cellphone
        message.save()

        try
        {
            println "before sendmessage"
            SendSmsResponse response = sendSMSService.sendSms(cellphone, signName, template, params.toString())
            println "after sendMessage"
            if (null != response && response.getCode().equals("OK"))
            {
                message.status = "Succesful"
                message.returnCode = response.getCode()
                message.save()
                return true;
            } else
            {
                println("短信发送失败，号码：" + cellphone + "模板：" + template + "数据：" + params + "原因：" + response.getMessage());
                message.status = "Failed"
                message.returnCode = response.getCode()
                message.returnMessage = response.getMessage()
                message.save()
            }
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }

        return false;
    }
}

//http://101.200.29.88:8082/SendMT/SendMessage?CorpID=1001&Pwd=123&Mobile=XXX&Content=%D%E
